package cn.virens.util.poi.read;

import java.io.Serializable;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

import cn.virens.util.poi.exception.ExcelException;

public class CellReader<D> implements Serializable {
	private static final long serialVersionUID = 1L;

	private int index;
	private String name;
	private ReadListener<D> listener;

	public int getIndex() {
		return index;
	}

	public void setIndex(int index) {
		this.index = index;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public ReadListener<D> getReadListener() {
		return listener;
	}

	public void setReadListener(ReadListener<D> mReadListener) {
		this.listener = mReadListener;
	}

	public D read(Row row, CellObject<D> cellObject) throws ExcelException {
		return listener.read(row.getCell(index), cellObject);
	}

	public CellObject<D> read(Row row, RowObject rowObject) {
		CellObject<D> cellObject = rowObject.createObject(this);

		try {
			cellObject.setObject(read(row, cellObject));
		} catch (ExcelException exception) {
			cellObject.setException(exception);
		}

		return cellObject;
	}

	public interface ReadListener<D> {
		public D read(Cell cell, CellObject<D> cellObject) throws ExcelException;
	}
}
